// renderExportForm.ts
import { ref, h } from 'vue'
import {
  Form,
  FormItem,
  Input,
  Row,
  Col,
  Button,
  Table,
  Spin,
  Divider,
  message,
  Popconfirm,
} from 'ant-design-vue'
import PdfImg from '@/assets/imgs/pdf.png'
import WarnImg from '@/assets/imgs/warn.png'
import { cloneDeep } from 'lodash-es'

// 最终导出渲染函数
export const renderExportForm = (apiData = {}, pdf_url, pdf_size) => {
  // 表单数据对象
  const formData = ref({
    // 基础信息
    country: '',
    terms: '',
    pieces: '',
    freight: '',
    packageType: '',
    miscFee: '',
    insurance: '',
    grossWeight: '',
    netWeight: '',
    receiver: '',

    // 商品信息（数组）
    products: [],
  })

  // 在 renderExportForm 函数内添加编辑状态
  const editableData = ref({})

  // 编辑相关方法
  const edit = (key) => {
    editableData.value[key] = cloneDeep(formData.value.products.find((item) => key === item.项号))
  }

  const save = (key) => {
    const index = formData.value.products.findIndex((item) => key === item.项号)
    if (index > -1) {
      Object.assign(formData.value.products[index], editableData.value[key])
      delete editableData.value[key]
      message.success('保存成功')
    }
  }

  const cancel = (key) => {
    delete editableData.value[key]
  }

  // 如果有API数据，则填充表单
  if (apiData) {
    formData.value = {
      country: apiData['贸易国（地区）'] || '',
      terms: apiData['成交方式'] || '',
      pieces: apiData['件数'] || '',
      freight: apiData['运费'] || '',
      packageType: apiData['包装种类'] || '',
      miscFee: apiData['杂费'] || '',
      insurance: apiData['保费'] || '',
      grossWeight: apiData['毛重（公斤）'] || '',
      netWeight: apiData['净重（公斤）'] || '',
      receiver: apiData['境外收货人'] || '',
      products: apiData['商品'] || [],
    }
  }

  // 基础信息字段配置
  const basicFields = [
    { label: '贸易国（地区）', name: 'country', span: 6, required: true },
    { label: '成交方式', name: 'terms', span: 6, required: true },
    { label: '件数', name: 'pieces', span: 6, required: true },
    { label: '运费', name: 'freight', span: 6, required: true },
    { label: '包装种类', name: 'packageType', span: 6, required: true },
    { label: '杂费', name: 'miscFee', span: 6, required: true },
    { label: '保费', name: 'insurance', span: 6, required: true },
    { label: '毛重（公斤）', name: 'grossWeight', span: 6, required: true },
    { label: '净重（公斤）', name: 'netWeight', span: 6, required: true },
    { label: '境外收货人', name: 'receiver', span: 12, required: true },
  ]

  // 渲染基础信息表单项
  const renderBasicFormItems = () => {
    const rows = []
    for (let i = 0; i < basicFields.length; i += 4) {
      const cols = basicFields.slice(i, i + 4).map((field) =>
        h(Col, { span: field.span }, () =>
          h(
            FormItem,
            {
              label: h('span', { style: 'font-weight: bold;' }, [field.label]),
              name: field.name,
              required: field.required, // 添加必填标记
              rules: [{ required: field.required, message: `请输入${field.label}` }], // 添加校验规则
            },
            {
              default: () =>
                h(Input, {
                  value: formData.value[field.name],
                  'onUpdate:value': (val) => (formData.value[field.name] = val),
                  placeholder: `请输入${field.label}`,
                  status: !formData.value[field.name] ? 'error' : '', // 添加错误状态
                }),
            },
          ),
        ),
      )
      rows.push(h(Row, { gutter: 16 }, () => cols))
    }
    return rows
  }

  // 商品表格列配置
  const renderEditableCell =
    (dataIndex) =>
    ({ text, record }) => {
      const editable = editableData.value[record.项号]
      return h('div', [
        editable
          ? h(Input, {
              value: editableData.value[record.项号][dataIndex],
              'onUpdate:value': (val) => {
                editableData.value[record.项号][dataIndex] = val
              },
              style: { margin: '-5px 0' },
            })
          : text,
      ])
    }

  const productColumns = [
    {
      title: '项号',
      dataIndex: '项号',
      key: '项号',
      width: 80,
    },
    {
      title: '商品名称',
      dataIndex: '商品名称',
      key: '商品名称',
      width: 150,
      customRender: renderEditableCell('商品名称'),
    },
    {
      title: '品牌型号',
      dataIndex: '品牌型号',
      key: '品牌型号',
      width: 120,
      customRender: renderEditableCell('品牌型号'),
    },
    {
      title: '商品编号',
      dataIndex: '商品编号',
      key: '商品编号',
      width: 120,
      customRender: renderEditableCell('商品编号'),
    },
    {
      title: '境内货源地',
      dataIndex: '境内货源地',
      key: '境内货源地',
      width: 120,
      customRender: renderEditableCell('境内货源地'),
    },
    {
      title: '尺寸',
      dataIndex: '尺寸',
      key: '尺寸',
      width: 150,
      customRender: renderEditableCell('尺寸'),
    },
    {
      title: '材质',
      dataIndex: '材质',
      key: '材质',
      width: 200,
      customRender: renderEditableCell('材质'),
    },
    {
      title: '用途',
      dataIndex: '用途',
      key: '用途',
      width: 120,
      customRender: renderEditableCell('用途'),
    },
    {
      title: '数量',
      dataIndex: '数量',
      key: '数量',
      width: 100,
      customRender: renderEditableCell('数量'),
    },
    {
      title: '单价',
      dataIndex: '单价',
      key: '单价',
      width: 100,
      customRender: renderEditableCell('单价'),
    },
    {
      title: '总价',
      dataIndex: '总价',
      key: '总价',
      width: 100,
      customRender: renderEditableCell('总价'),
    },
    {
      title: '重量',
      dataIndex: '重量',
      key: '重量',
      width: 80,
      customRender: renderEditableCell('重量'),
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: 120,
      fixed: 'right',
      customRender: ({ record }) => {
        const editable = editableData.value[record.项号]
        return h('div', { class: 'editable-row-operations' }, [
          editable
            ? h('span', [
                h(
                  'a',
                  {
                    class: 'mr-2 !text-[#2BC155]',
                    onClick: () => save(record.项号),
                  },
                  '保存',
                ),
                h(
                  Popconfirm,
                  {
                    title: '确定要取消吗？',
                    onConfirm: () => cancel(record.项号),
                  },
                  {
                    default: () => h('a', { class: '!text-[#ff4d4f]' }, '取消'),
                  },
                ),
              ])
            : h(
                'a',
                {
                  onClick: () => edit(record.项号),
                },
                '编辑',
              ),
        ])
      },
    },
  ]

  // 控制下载区域显示和加载动画
  const showDownload = ref(false)
  const loading = ref(false)
  const downloadLoading = ref(false)

  // 下载区域
  const renderDownload = () => {
    // 下载函数
    const handleDownload = async () => {
      downloadLoading.value = true
      try {
        const response = await fetch(pdf_url, { mode: 'cors' })
        if (!response.ok) throw new Error('下载失败')
        const blob = await response.blob()
        const blobUrl = window.URL.createObjectURL(blob)
        // 生成时间戳
        const now = new Date()
        const pad = (n) => n.toString().padStart(2, '0')
        const timeStr = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}_${pad(now.getHours())}${pad(now.getMinutes())}`
        const fileName = `出口货物明细单_${timeStr}.pdf`
        const a = document.createElement('a')
        a.href = blobUrl
        a.download = fileName
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
        window.URL.revokeObjectURL(blobUrl)
        message.success('下载完成！')
      } catch (e) {
        message.error('下载失败，请重试')
      } finally {
        downloadLoading.value = false
      }
    }

    return h('div', { class: 'w-full justify-between items-center flex mt-6 pr-8' }, [
      h(
        'div',
        {
          class:
            'flex items-center shadow-md rounded-md px-4 py-3 bg-[rgba(0,0,0,0.06)]  w-[260px]',
        },
        [
          // 左侧：文件信息
          h('div', { class: 'flex flex-col justify-center flex-1' }, [
            h('div', { class: 'mb-1 font-bold' }, '出口货物明细单.pdf'),
            h('div', { class: 'text-xs text-gray-500' }, `文件大小：${pdf_size}KB`),
          ]),
          // 右侧：PDF图片
          h('img', {
            src: PdfImg,
            alt: 'pdf',
            class: 'w-10 h-10 ml-4',
          }),
        ],
      ),
      h(
        Button,
        {
          onClick: handleDownload, // 关键：点击下载
          type: 'primary',
          loading: downloadLoading.value,
          disabled: downloadLoading.value,
        },
        { default: () => '下载' },
      ),
      downloadLoading.value && h(Spin, { class: 'ml-2', size: 'small', tip: '正在下载...' }),
    ])
  }

  // 检查是否有空值
  const hasEmptyField = () => {
    // 检查基础信息
    const basicFieldsEmpty = basicFields.some(
      (f) => !formData.value[f.name] || String(formData.value[f.name]).trim() === '',
    )

    // 检查商品信息
    const productsEmpty = !formData.value.products || formData.value.products.length === 0

    return basicFieldsEmpty || productsEmpty
  }

  // 计算商品总金额
  const getTotalAmount = () => {
    if (!formData.value.products || formData.value.products.length === 0) return '0'

    const total = formData.value.products.reduce((sum, product) => {
      const amount = parseFloat(product['总价']?.replace(/[^\d.]/g, '') || 0)
      return sum + amount
    }, 0)

    return total.toFixed(2)
  }

  // 返回渲染函数
  return () =>
    h('div', { class: 'mb-20' }, [
      h('div', { class: 'mb-4 font-bold' }, '聊天记录已解析：'),
      h(
        Form,
        {
          layout: 'vertical',
          class: 'border border-[#ECEFF8] shadow-md rounded-md bg-white !p-8',
          model: formData.value,
        },
        {
          default: () => [
            // 基础信息区域
            h('div', { class: 'mb-6' }, [
              h('h3', { class: 'text-lg font-bold mb-4' }, '基础信息'),
              ...renderBasicFormItems(),
            ]),

            // 商品信息区域
            h('div', { class: 'mb-6' }, [
              h('h3', { class: 'text-lg font-bold mb-4' }, '商品信息'),
              h('div', { class: 'mb-2 text-sm text-gray-600' }, [
                `共 ${formData.value.products?.length || 0} 项商品，总金额：${getTotalAmount()} USD`,
              ]),
              h(Table, {
                columns: productColumns,
                dataSource: formData.value.products || [],
                pagination: false,
                size: 'small',
                scroll: { x: 1200 },
                bordered: true,
              }),
            ]),

            // 验证和操作区域
            hasEmptyField()
              ? h('div', { class: 'flex items-center mt-4' }, [
                  h('img', {
                    src: WarnImg,
                    alt: '警告',
                    class: 'w-5 h-5 mr-2',
                  }),
                  h('span', { class: 'text-red-600' }, '警告：识别到表单存在未填写项'),
                ])
              : h('div', { class: 'flex items-center justify-between mt-4' }, [
                  h(
                    'div',
                    { class: 'text-sm font-bold' },
                    '校验完成，如需修改或补充其他信息，请上传或编辑更正内容！核对所有信息无误可点击按钮生成出口货物明细单。',
                  ),
                  !showDownload.value &&
                    h(
                      Button,
                      {
                        loading: loading.value,
                        disabled: loading.value || showDownload.value,
                        type: 'primary',
                        class: 'ml-4',
                        onClick: async () => {
                          if (showDownload.value) return
                          loading.value = true
                          setTimeout(() => {
                            loading.value = false
                            showDownload.value = true
                          }, 2000)
                        },
                      },
                      { default: () => (loading.value ? '正在生成...' : '生成') },
                    ),
                  showDownload.value &&
                    h(
                      Button,
                      {
                        type: 'primary',
                        class: 'ml-4',
                        disabled: true,
                      },
                      { default: () => '已生成' },
                    ),
                ]),
          ],
        },
      ),
      loading.value
        ? h('div', { class: 'flex justify-center items-center mt-8' }, [
            h(Spin, { tip: '正在生成PDF，请稍候...' }),
          ])
        : null,
      showDownload.value ? renderDownload() : null,
    ])
}
